package com.huifaapp.mall.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.GoodsListXRVAdapter;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.GoodsClassifyListData;
import com.huifaapp.mall.fragment.TmallClassifyBaseFragment;
import com.huifaapp.mall.uitils.Contig;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;

/**
 * Created by DM on 2018/1/29.
 */
@SuppressLint("ValidFragment")
public class TmallClassifyWithSPBJ extends TmallClassifyBaseFragment  implements View.OnClickListener{
    private Context context;
    private View view;
    private XRecyclerView jkbjXRV;
    private List<GoodsClassifyListData.DataBean.ListBean> listBeanList = new ArrayList<>();
    private GoodsListXRVAdapter goodsListXRVAdapter;
    private String categroyId;
    private int start = 0;
    private int lastOffset;
    private int lastPosition;
    private LinearLayout mActivity;
    private TextView mActivityTv;
    private TextView mProductTv;
    private LinearLayout mProduct;
    private TextView mSortTv;
    private LinearLayout mSort;
    private ListView mPopListView;
    private PopupWindow mPopupMenu;
    private SimpleAdapter mMenuAdapter1;
    private SimpleAdapter mMenuAdapter3;
    private ArrayList <Map<String, String> >mMenuData3;
    private ArrayList mMenuData2;
    private  ArrayList <Map<String, String> > mMenuData1;
    private int menuIndex = 0;
    boolean flag=true;
    private List<GoodsClassifyListData.DataBean.ListBean> goods;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            view = inflater.inflate(R.layout.fragment_jkbj, container, false);
            initView();
            //ButterKnife的初始化
            ButterKnife.bind(getActivity());
            //初始化Popuwindow显示的数据
            initDatapopw();
            //初始化popuwindow控件
            initPopMenu();
            initAdapter("");
            initData(start, "");
        }catch (Exception e){

        }
        return view;
    }
    private void initPopMenu() {
        try {
            //把包裹的ListVIew的布局XML文件转换为VIew对象
            View popView = LayoutInflater.from(getActivity()).inflate(R.layout.popwin_supplier_list, null);
            //创建popuwindow对象,参数1popuwindow要显示的布局,参数2,3:定义popuwindow所占用的宽高
            mPopupMenu = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            //设置popuwindow外部可以点击              true:可以，      false:不可以
            mPopupMenu.setOutsideTouchable(true);
            //是popuwindow里填充的listView拥有焦点
            mPopupMenu.setFocusable(true);
            //如果想要让popuwindow具有一些操作,比如动画效果之类的,必须给popuwindow设置背景
            mPopupMenu.setBackgroundDrawable(new ColorDrawable());
            //设置popuwindow的动画效果
//          mPopupMenu.setAnimationStyle(R.style.popwin_anim_style);
            //设置popuwindow结束时的监听事件
            mPopupMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    //设置TextView的颜色,把所有LinearLayout的文本颜色该为灰色
                    mProductTv.setTextColor(Color.parseColor("#5a5959"));
                    mSortTv.setTextColor(Color.parseColor("#5a5959"));
                    mActivityTv.setTextColor(Color.parseColor("#5a5959"));
                }
            });
            //点击popuwindow以外的区域,使popuwindow消失(实际就是让ListView下面的LinerLayout,设置点击事件)
            LinearLayout list_bottom = (LinearLayout) popView.findViewById(R.id.popwin_supplier_list_bottom);
            list_bottom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //当LinerLayout被点击时,这popuwindow消失
                    mPopupMenu.dismiss();
                }
            });

            //获取listVIew对象
            mPopListView = (ListView) popView.findViewById(R.id.popwin_supplier_list_lv);
            //点击popuwindow以外区域时,使popuwindow消失.在这里得到了ListView下面的LinearLayout,设置监听事件
            /*SimpleAdapter 简单数据适配器:正好有一组数据,是Map集合放到ArrayList集合,就可以使用这个适配器了,不是太常用,设置数据太麻烦.
            context:上下文    data:设置所有条目的数据,一个ArrayList大集合(包含所有条目信息),里面又有一个map集合(通过map来设置一个条目的数据)
            resource:引用布局资源(可以引用复杂的布局.xml文件,区别于ArrayAdapter)
            from:String数组,装map条目内容的键            to:int数组,装控件id  二者具有映射关系,代表对应的内容放到对应的位置*//*
            ArrayList<Map<String,Object>> data=new ArrayList<Map<String,Object>>();
        //注意:一个map,代表一条item的数据.
        Map<String,Object> map=new HashMap<String, Object>();
        ListView对象.setAdapter(new SimpleAdapter(context, data, resource, from, to));*/
            //创建SimpleAdapter,一个listView安卓原生封装的适配器
            mMenuAdapter1 = new SimpleAdapter(getActivity(), mMenuData1,
                    R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});
            mSort.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initData(0, "totalSalesDesc");
                    initAdapter("totalSalesDesc");
                }
            });

//        mMenuAdapter2 = new SimpleAdapter(this, mMenuData2,
//                R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});

            mMenuAdapter3 = new SimpleAdapter(getActivity(), mMenuData3,
                    R.layout.item_listview_popwin, new String[]{"name"}, new int[]{R.id.listview_popwind_tv});

            //设置Popuwindow里的listView点击事件,当点击listVIew里的一个item时,把这个item数据显示到最上方
            mPopListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long ld) {
                    //首先让Popuwindow消失
                    mPopupMenu.dismiss();
                    //设置一个标识,以方便做对应LinerLayout的点击事件.
                    switch (menuIndex) {
                        case 0:
                            //获取点击对应条目的文本数据
                            String currentProduct = mMenuData1.get(position).get("name");
                            //把文本数据设置到原始布局里的文本
                            if (currentProduct.equals("价格由高到低")) {
                                initData(0, "priceDesc");
                                initAdapter("priceDesc");
                            }
                            if (currentProduct.equals("价格由低到高")) {
                                initData(0, "priceAsc");
                                initAdapter("priceAsc");
                            }

                            mProductTv.setText(currentProduct);
                            break;
                        case 2:
                            String currentAct = mMenuData3.get(position).get("name");

                            if (currentAct.equals("红包由高到低")) {
                                initData(0, "couponMoneyDesc");
                                initAdapter("couponMoneyDesc");
                            }
                            if (currentAct.equals("红包由低到高")) {
                                initData(0, "couponMoneyAsc");
                                initAdapter("couponMoneyAsc");
                            }
                            mActivityTv.setText(currentAct);
//                            initData(start, currentAct);
//                            initAdapter(currentAct);
                            break;
                        default:
                            break;
                    }
                }
            });
        }catch (Exception e){}
    }
    private void initDatapopw() {
        try {
            mMenuData1 = new ArrayList<>();
            //存放String的字符串数组
            String[] menuStr1 = new String[]{"综合排序", "价格由高到低", "价格由低到高"
            };
            //创建一个小盒子,放编号和值
            Map<String, String> map1;
            for (int i = 0, len = menuStr1.length; i < len; ++i) {
                map1 = new HashMap<String, String>();
                map1.put("name", menuStr1[i]);
                mMenuData1.add(map1);
            }
            //创建一个存放popupwindow加载数据的大盒子2,Map集合(键,值)
            mMenuData2 = new ArrayList<>();
            String[] menuStr2 = new String[]{};
            Map<String, String> map2;
            for (int i = 0, len = menuStr2.length; i < len; ++i) {
                map2 = new HashMap<String, String>();
                map2.put("name", menuStr2[i]);
                mMenuData2.add(map2);
            }
            //创建一个存放popupwindow加载数据的大盒子3,Map集合(键,值)
            mMenuData3 = new ArrayList<>();
            String[] menuStr3 = new String[]{"红包由高到低", "红包由低到高"};
            Map<String, String> map3;
            for (int i = 0, len = menuStr3.length; i < len; ++i) {
                map3 = new HashMap<String, String>();
                map3.put("name", menuStr3[i]);
                mMenuData3.add(map3);
            }
        }catch (Exception e){}
    }
    private void initData(int start,String orderType) {
        try {


        final String url = ApiManager.BASE_NIUPAI_URL+"goods/list";
            Log.e("url",url);
        OkHttpUtils
                .get()
                .url(url)
                .addParams("categoryId", "")
                .addParams("start",start+"")
                .addParams("orderType",orderType)
                .addParams("type",Contig.typex)
                .addParams("categoryCode",Contig.categrouCode)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Log.e("error",e.toString());
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.e("response",response);

                        Gson gson = new Gson();
                        GoodsClassifyListData goodsClassifyListData =
                                gson.fromJson(response, GoodsClassifyListData.class);
                        if (goodsClassifyListData.getCode().equals("10000")) {

                            goodsListXRVAdapter.setListBeans(goods);
                            goodsListXRVAdapter.notifyDataSetChanged();

                        }else{
                            Toast.makeText(getActivity(),goodsClassifyListData.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        }catch (IllegalArgumentException e){

        }
    }

    private void initAdapter(final String orderType) {
        try {
            StaggeredGridLayoutManager staggeredGridLayoutManager =
                    new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
            jkbjXRV.setLayoutManager(staggeredGridLayoutManager);
            goodsListXRVAdapter =
                    new GoodsListXRVAdapter(getActivity());
            jkbjXRV.setAdapter(goodsListXRVAdapter);
            jkbjXRV.setLoadingListener(new XRecyclerView.LoadingListener() {
                @Override
                public void onRefresh() {
                    //这里执行下拉刷新逻辑
                    start = 0;
                    initData(start, orderType);
//                    goodsListXRVAdapter.getListBeans().clear();
                }

                @Override
                public void onLoadMore() {
                    //这里执行上拉加载逻辑
//                    start++;
                    initData(++start, orderType);
                    scrollToPosition();
                }
            });
            //监听RecyclerView滚动状态
            jkbjXRV.addOnScrollListener(new XRecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (recyclerView.getLayoutManager() != null) {
                        getPositionAndOffset();
                    }
                }
            });
        }catch (IllegalArgumentException e){

        }
    }
    /**
     * 记录RecyclerView当前位置
     */
    private void getPositionAndOffset() {
        try {
            StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) jkbjXRV.getLayoutManager();
            //获取可视的第一个view
            View topView = layoutManager.getChildAt(0);
            if (topView != null) {
                //获取与该view的顶部的偏移量
                lastOffset = topView.getTop();
                //得到该View的数组位置
                lastPosition = layoutManager.getPosition(topView);
            }
        }catch (Exception e){}
    }
    /**
     * 让RecyclerView滚动到指定位置
     */
    private void scrollToPosition() {
        try {
            if (jkbjXRV.getLayoutManager() != null && lastPosition >= 0) {
                ((StaggeredGridLayoutManager) jkbjXRV.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
            }
        }catch (Exception e){

        }
    }
    private void initView() {
        try {
            jkbjXRV = (XRecyclerView) view.findViewById(R.id.jkbj_xrv);
            mActivity = (LinearLayout) view.findViewById(R.id.fragment_jkbj_activity);
            mActivity.setOnClickListener(this);
            mActivityTv = (TextView) view.findViewById(R.id.fragment_jkbjas_tv);
            mProductTv = (TextView) view.findViewById(R.id.fragment_jkbj_tv);
            mProduct = (LinearLayout) view.findViewById(R.id.fragment_jkbj_ll);
            mProduct.setOnClickListener(this);

            mSortTv = (TextView) view.findViewById(R.id.fragment_jkbjs_tv);
            mSortTv.setOnClickListener(this);
            mSort = (LinearLayout) view.findViewById(R.id.fragment_jkbj_sort);
            mSort.setOnClickListener(this);

            mSortTv.setTextColor(Color.parseColor("#5a5959"));
//            if(flag){
//                mSortTv.setTextColor(Color.parseColor("#5a5959"));
//                flag=true;
//            }else{
//                mSortTv.setTextColor(Color.parseColor("#ff2040"));
//                flag=false;
//            }
        }catch (Exception e){

        }
    }
    public void onClick(View view){
        try {
            switch (view.getId()) {
                //第一个Popuwindow所执行的点击后的逻辑
                case R.id.fragment_jkbj_ll:
                    mSortTv.setTextColor(Color.parseColor("#5a5959"));
                    //设置其TextView点击时为绿色
                    mProductTv.setTextColor(Color.parseColor("#ff2040"));
                    //设置Popuwindow里的ListView适配器
                    mPopListView.setAdapter(mMenuAdapter1);
                    //让Popuwindow显示出来.  参数1:VIew对象,决定了在哪个控件下显示,  参数2决定了Popuwindow的坐标,X轴,Y轴
//                mPopupMenu.showAsDropDown(mProduct);
                    mPopupMenu.showAsDropDown(mProduct, 0, 0, Gravity.BOTTOM);
                    menuIndex = 0;
                    break;
                //第2个Popuwindow所执行的点击后的逻辑
                case R.id.fragment_jkbj_sort:
//                mSortTv.setTextColor(Color.parseColor("#39ac69"));
//                mPopListView.setAdapter(mMenuAdapter2);
//                mPopupMenu.showAsDropDown(mSort);
//                   flag=true;

                    menuIndex = 1;
                    break;
                case R.id.fragment_jkbjs_tv:
//                    flag=true;
                    mSortTv.setTextColor(Color.parseColor("#ff2040"));
                    menuIndex = 1;
                    break;
                //第3个Popuwindow所执行的点击后的逻辑
                case R.id.fragment_jkbj_activity:
                    mSortTv.setTextColor(Color.parseColor("#5a5959"));
                    mActivityTv.setTextColor(Color.parseColor("#ff2040"));
                    mPopListView.setAdapter(mMenuAdapter3);
//                mPopupMenu.showAsDropDown(mActivity);
                    mPopupMenu.showAsDropDown(mProduct, 0, 0, Gravity.BOTTOM);
                    menuIndex = 2;
                    break;

                default:
                    break;
            }
        }catch (Exception e){

        }
    }
}
